/** fichier libsck.c **/

/* Fichier d'inclusion */
#include "libsck.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
extern int h_errno;
/* Constantes internes */

#define NBCONNEXIONS 100
/* Initialisation de la communication réseau */
int initialisationServeur(unsigned short int *port)
{
	int idSocket;
	if ((idSocket=socket(AF_INET,SOCK_STREAM,0))==-1){
		perror("socket");
		exit(-1);
	}
    int optval = 1;
    setsockopt(idSocket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
	struct sockaddr_in addresse;
	addresse.sin_family=AF_INET;
	addresse.sin_port=htons(*port);
	addresse.sin_addr.s_addr=INADDR_ANY;
	if (bind(idSocket,(struct sockaddr*)(&addresse),sizeof(struct sockaddr_in))==-1){
		perror("bind");
		exit(-1);
	}
	return idSocket;

}


/* boucle d'attente des connexions */
/* a chaque connexion, lancment de la fonction "fonction" avec comme paramètre, socket et client */
int boucleServeur(int socket, void (*function)(void *, void*(*)(void*)), void*(*function2)(void*))
{
	if (listen(socket,NBCONNEXIONS)==-1){
		perror("listen");
		exit(-1);
	}
	struct sockaddr_in adresse;
	socklen_t taille=sizeof(adresse);
	while (1){
		int dialogue;
		if ((dialogue=accept(socket,(struct sockaddr *)&adresse,&taille))==-1){
			perror("accept");
			exit(-1);
		}
		function(&dialogue,function2);
	}
}

char * SocketVersNom(int socket){
	struct sockaddr_in addresse;
	socklen_t length=sizeof(addresse);
	if (getpeername(socket,(struct sockaddr *)&addresse,&length)==-1){
		perror("getpeername");
		exit(-1);
	}
	struct hostent * hostent;
	if ((hostent=gethostbyaddr(&addresse,length,AF_INET))==0){
			perror("hostent");
			exit(-1);
	}
	char *name=calloc(strlen(hostent->h_name)+1,sizeof(char));
	memcpy(name,hostent->h_name,(strlen(hostent->h_name)+1)*sizeof(char));
	return name;
}

